import React, {Component, Fragment} from 'react'
import {Input, Button, List} from 'antd'
import './TodoList.css';
import store from './store'
import {getAddTodoItemAction, getChangeInputValueAction, getDeleteActionAction} from './store/actionCreator';

class TodoList extends Component {
    constructor(props) {
        super(props)
        this.state = store.getState();
        this.handleInputChange = this.handleInputChange.bind(this)
        this.handleStoreChange = this.handleStoreChange.bind(this)
        store.subscribe(this.handleStoreChange)
        this.handleBtnChange = this.handleBtnChange.bind(this)
    }

    render() {
        return (
            <Fragment>
                <Input.Group compact>
                    <Input style={{width: '300px'}} placeholder='todo info' value={this.state.inputValue}
                           onChange={this.handleInputChange}/>
                    <Button type="primary" onClick={this.handleBtnChange}>Submit</Button>
                </Input.Group>
                <List
                    size="small"
                    style={{width: '300px'}}
                    bordered
                    dataSource={this.state.list}
                    renderItem={(item, index) => <List.Item
                        onClick={this.handleItemClick.bind(this, index)}>{item}</List.Item>}
                />
            </Fragment>
        )
    }

    handleInputChange(e) {
        const action = getChangeInputValueAction(e.target.value)
        store.dispatch(action)
    }

    handleStoreChange() {
        this.setState(store.getState())
    }

    handleBtnChange() {
        const action = getAddTodoItemAction();
        store.dispatch(action)
    }

    handleItemClick(index) {
        const action=getDeleteActionAction(index)
        store.dispatch(action)
    }
}

export default TodoList
